package com.chart.web.controller.aiText;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
public class IPController {

    private static final String API_URL = "https://api.map.baidu.com/location/ip?";
    private static final String AK = "cfne0IDH4FDyJabdFlXGsfOrw6fcq5Xq"; // 替换为您的百度地图开发者密钥

    /**
     * 根据 IP 获取城市的行政区划代码 (adcode)
     *
     * @return 城市的行政区划代码 (adcode)
     */
    @GetMapping("/getLocation")
    public String getAdcode() {
        try {
            // 构建请求参数
            Map<String, String> params = new LinkedHashMap<>();
            params.put("ip", "111.206.214.37"); // 如果为空，则默认获取请求方的 IP
            params.put("coor", "bd09ll"); // 坐标类型
            params.put("ak", AK); // 开发者密钥

            // 发起 API 调用
            String response = requestGet(API_URL, params);

            // 解析 JSON 数据，提取 adcode
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(response);

            JsonNode contentNode = rootNode.path("content");
            JsonNode addressDetailNode = contentNode.path("address_detail");
            String adcode = addressDetailNode.path("adcode").asText();
            String cityCode = addressDetailNode.path("city_code").asText();
            JsonNode pointNode = contentNode.path("point");
        // 格式化 X 和 Y 坐标保留两位小数
            DecimalFormat df = new DecimalFormat("#.##");
            String x = df.format(pointNode.path("x").asDouble());
            String y = df.format(pointNode.path("y").asDouble());


            String xy=x+","+y;
            return xy;


        } catch (Exception e) {
            e.printStackTrace();
            return "{\"error\":\"Failed to fetch adcode\"}";
        }
    }

    /**
     * 调用百度地图 API
     *
     * @param strUrl 请求的基础 URL
     * @param params 请求的参数
     * @return API 返回的 JSON 数据
     * @throws Exception 异常捕获
     */
    private String requestGet(String strUrl, Map<String, String> params) throws Exception {
        // 构建完整 URL
        StringBuilder queryString = new StringBuilder(strUrl);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            queryString.append(entry.getKey())
                    .append("=")
                    .append(UriUtils.encode(entry.getValue(), "UTF-8"))
                    .append("&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1); // 移除最后一个多余的 "&"
        }

        // 发起 HTTP 请求
        URL url = new URL(queryString.toString());
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestMethod("GET");

        // 读取响应
        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream(), "UTF-8");
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        isr.close();

        return response.toString();
    }
}
